package java_code;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {//JDBCUtils.properties
    //读取配置文件的内容到这来把下面的字符串替换,解决硬编码问题
    static String diverclass;
    static String url;//null
    static String user;//null
    static String password;//null

    static {
        try {
            //p.
            Properties p = new Properties();
            //file
//            FileInputStream fis = new FileInputStream("D:\\JAVA\\Poject\\java\\src\\java_code\\JDBCUtils.properties");
            //扩展,.class文件的类加载器对象,能把类.class硬盘加载到内存,里面有输入流,默认读取src文件夹,只需要写src下面的文件路径即可
            InputStream fis = JDBCUtils.class.getClassLoader().getResourceAsStream("java_code\\JDBCUtils.properties");

            p.load(fis);//文件的键和值在p里面
            diverclass = p.getProperty("diverclass");
            url = p.getProperty("url");
            user = p.getProperty("user");
            password = p.getProperty("password");

            //Class.forName("com.mysql.jdbc.Driver");//Driver.class
            Class.forName(diverclass);//Driver.class
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        try {
            //Class.forName("com.mysql.jdbc.Driver");//Driver.class
            //Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "root");
            Connection connection = DriverManager.getConnection(url, user, password);
            return  connection;
        } catch(Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static void close(ResultSet resultSet,Statement statement,Connection connection) {
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        //connection.notnull
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
